package com.freely.ui.viewModel;

import android.util.Log;

import com.freely.component.BaseViewModel;
import com.freely.data.database.FreelyDatabase;
import com.freely.data.entities.Message;
import com.freely.data.network.FreelyClient;
import com.freely.data.network.ServerException;
import com.freely.data.network.requestEntities.RQUserId;
import com.freely.data.network.responseEntities.RSResult;
import com.freely.data.network.webSocket.MessageListener;
import com.freely.ui.util.ErrorUtil;
import com.google.gson.reflect.TypeToken;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import androidx.lifecycle.MutableLiveData;
import io.reactivex.Single;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;
import okhttp3.WebSocket;

/**
 * @author DaWan
 * @time 2018/12/2 11:25
 * @dscription
 */
public class MessageViewModel extends BaseViewModel {
	private static final String TAG = "MessageViewModel";
	private long userId;
	private List<Long> groupIds = new ArrayList<>();
	private MutableLiveData<List<Message>> messageList = new MutableLiveData<>();
	private WebSocket webSocket = FreelyClient.getWebSocket();
	private MessageListener listener = (type, data) -> {
		if (type != 1) {
			return false;
		}
		List<Message> messages = FreelyClient.getGson()
				.fromJson(data, new TypeToken<List<Message>>() {}.getType());
		Log.d(TAG, ": "+messages);
		Log.d(TAG, ": "+messageList.getValue());
		List<Message> list = messageList.getValue();
		list.addAll(messages);
		messageList.postValue(list);
		FreelyDatabase.getInstance().messageDAO().insertMessage(messages);
		return true;
	};

	public MessageViewModel() {
		FreelyClient.getWebSocketManager().addListener(listener);
	}

	public void loadMessageList(long userId) {
		Single<List<Message>> single = FreelyDatabase.getInstance()
				.messageDAO()
				.queryAllMessageByUserId(userId);

		Disposable disposable = single.subscribeOn(Schedulers.io())
				.subscribe(messages -> {
					if (messages.isEmpty()) {
						loadAllMessageForInternet(userId);
						return;
					}
					messageList.postValue(messages);
					loadNewMessagesForInternet(userId);
				}, ErrorUtil::errorHint);

		register(disposable);
	}

	public void loadAllMessageForInternet(long userId) {
		Single<RSResult<List<Message>, String>> single = FreelyClient.getFreelyService()
				.allMessage(new RQUserId(userId));

		Disposable disposable = single.subscribeOn(Schedulers.io())
				.subscribe(result -> {
					if (!result.isResult()) {
						ErrorUtil.errorHint(new ServerException(result.getFailure()));
						return;
					}
					List<Message> messages = result.getSuccess();
					messageList.postValue(messages);
					FreelyDatabase.getInstance().messageDAO().insertMessage(messages);
				},ErrorUtil::errorHint);

		register(disposable);
	}

	public void loadNewMessagesForInternet(long userId) {
		Date date = FreelyDatabase.getInstance()
				.messageDAO()
				.queryNewMessage(userId)
				.blockingGet()
				.getMessageSendTime();
		Map<String, Object> parameter = new HashMap<>();
		parameter.put("data_type", 0);
		parameter.put("user_id", userId);
		parameter.put("user_last_login_time", date.getTime());
		webSocket.send(FreelyClient.getGson().toJson(parameter));
	}

	@Override
	protected void onCleared() {
		super.onCleared();
		FreelyClient.getWebSocketManager().removeListener(listener);
	}

	public MutableLiveData<List<Message>> getMessageList() {
		return messageList;
	}

	public long getUserId() {
		return userId;
	}

	public void setUserId(long userId) {
		this.userId = userId;
	}

	public List<Long> getGroupIds() {
		return groupIds;
	}
}
